﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Eamon.MeituanDotnetSDK.@enum;
using Eamon.MeituanDotnetSDK.exception;
using Eamon.MeituanDotnetSDK.utils;

namespace Eamon.MeituanDotnetSDK.httpclient
{
    public class OpenAPIHttpClient
    {
        public OpenAPIHttpClient()
        {
            handler = new HttpClientHandler(){
                AllowAutoRedirect = true,
            };
            _client = new HttpClient(handler); 
            //_client.DefaultRequestHeaders.Add("User-Agent", _userAgent);
            //_client.DefaultRequestHeaders.Add("Connection", "keep-alive");
            //_client.DefaultRequestHeaders.Add("Accept-Charset", _charset); 
            //_client.DefaultRequestHeaders.Add("Accept-Language", _acceptLanguage);
            _client.DefaultRequestHeaders.Add("Sdk-Info", CommonConstants.SDK_VERSION);
        }

        public OpenAPIHttpClient(HttpClient httpClient){
            this._client = httpClient;
            this._client.DefaultRequestHeaders.Add("Sdk-Info", CommonConstants.SDK_VERSION);
        }

        public string exception;
        private readonly HttpClient _client;
        private HttpClientHandler handler;
   

        public string DeveloperId { set { ChangeHeaders("DeveloperId", value); } }
        private void ChangeHeaders(string name, string newHeaders)
        {
            _client.DefaultRequestHeaders.Remove(name);
            _client.DefaultRequestHeaders.Add(name, newHeaders);
        }
        public void SetBaseAddress(string url)
        {
            _client.BaseAddress = new Uri(url);
        }
        public void destroyClient()
        {
            try
            {
                if (this._client != null)
                {
                    _client.Dispose();
                }
            }
            catch (IOException ex)
            {
                throw new MtSdkException("distory httpClient error", ex);
            }
        }

        public async Task<string> GetResponse(string url , HttpMethodEnum httpMethod, Hashtable data, CancellationToken cancellationToken)
        {


            Uri uri = new Uri(url);
            HttpResponseMessage res = null;
            Dictionary<string, string> dics = new Dictionary<string, string>();
            foreach (DictionaryEntry kv in data)
            {
                dics.Add(kv.Key.ToString(), kv.Value.ToString());
            }
            try
            {
                if (httpMethod==HttpMethodEnum.GET)
                {
                    string param = buildHttpGetParameters(dics);

                    res = await _client.GetAsync(uri+"?"+param, cancellationToken);
                }
                else
                {
                    HttpContent content = new FormUrlEncodedContent(dics);
                    res = await _client.PostAsync(uri, content, cancellationToken);
                }

                if (res != null && res.IsSuccessStatusCode)
                {
                    try
                    {
                        return await res.Content.ReadAsStringAsync();
                    }
                    catch (Exception ex)
                    {
                        throw new MtSdkException("##http client result error", ex);
                    }
                }
                else
                {
                        exception = res == null ? "服务器不响应" : Enum.GetName(typeof(HttpStatusCode), res.StatusCode);
                        return null;

                    }
                }
            catch (Exception ex)
            {
                exception = ex.Message;
                return null;
            }
        }

        private string buildHttpGetParameters(Dictionary<string, string> pairs)
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach (var kv in pairs)
            {
                stringBuilder.Append(kv.Key).Append("=").Append(kv.Value).Append("&");
            }
            string str = stringBuilder.ToString();
            string result = str.Substring(0,str.Length - 1);
            return result;
        }
    }
}
